package com.kitty.web.system.gameServer;

import cn.hutool.core.lang.Assert;
import com.kitty.common.cache.RefreshCache;
import com.kitty.common.cache.entity.ActivityNumberSet;
import com.kitty.common.cache.entity.AppProperties;
import com.kitty.common.core.SchedulerManager;
import com.kitty.common.schedule.CronTaskRegistrar;
import com.kitty.common.schedule.entity.SpringScheduledCron;
import com.kitty.common.schedule.service.SpringScheduledCronService;
import com.kitty.common.schedule.task.ScheduledOfTask;
import com.kitty.common.start.MyApplicationRunner;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.ServerService;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.service.other.ZhengDaoDianHandler;
import com.kitty.game.activity.service.shidao.ShiDaoHandler;
import com.kitty.game.activity.service.time.XingGuanHandler;
import com.kitty.game.admin.service.AdminService;
import com.kitty.game.base.model.CommonSet;
import com.kitty.game.boss.service.NewBossService;
import com.kitty.game.chat.service.ChatService;
import com.kitty.game.config.LoginServer;
import com.kitty.game.config.PetSet;
import com.kitty.game.config.Server;
import com.kitty.game.drop.service.DropService;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.service.GSGService;
import com.kitty.game.fight.service.FightMessageService;
import com.kitty.game.fight.service.FightService;
import com.kitty.game.hunpo.service.HunPoService;
import com.kitty.game.market.MarketService;
import com.kitty.game.neidan.service.NeidanService;
import com.kitty.game.newchoujiang.service.NewChouJiangService;
import com.kitty.game.pet.PetDataPool;
import com.kitty.game.player.PlayerService;
import com.kitty.game.reward.service.RewardSetService;
import com.kitty.game.role.model.Account;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.AccountService;
import com.kitty.game.titleManage.service.TitleInfoService;
import com.kitty.game.utils.TimeUtil;
import com.kitty.game.welfare.service.ServenDayRewardHandler;
import com.kitty.game.wuhun.WuHunService_;
import com.kitty.game.zhenbao.ZhenbaoService;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import com.kitty.mina.session.SessionManager;
import com.kitty.web.common.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.session.IoSession;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.http.Request;
import org.nutz.http.Sender;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

@Service
@Slf4j
public class GameServerRefresh {

    public AjaxResult refreshCache(String type, String value, String state) {
        Response response =Response.ok();
        if(type.equals(RefreshType.delall.name())){

        }else if(type.equals(RefreshType.maintain.name())){
            response = maintain(state);
        }else if(type.equals(RefreshType.ceshi.name())){
            response = ceshi(state);
        }else if(type.equals(RefreshType.sealPhone.name())){
            response = sealPhone(value,state);
        }else if(type.equals(RefreshType.speak.name())){
            response = speak(value,state);
        }else if(type.equals(RefreshType.seal.name())){
            response = seal(value,state);
        }else if(type.equals(RefreshType.killPlayers.name())){
            response = killPlayers(value);
        }else if(type.equals(RefreshType.notice.name())){
            response = notice(value);
        }else if(type.equals(RefreshType.refreshDropInfo.name())){
            SpringUtils.getBean(DropService.class).loadProduct();
        }else if(type.equals(RefreshType.refreshChongZhiHaoLi.name())){
            SpringUtils.getBean(MyApplicationRunner.class).initChoujiang();
        }else if(type.equals(RefreshType.refreshOnLineMall.name())){
            SpringUtils.getBean(MyApplicationRunner.class).initOnlineMall();
        }else if(type.equals(RefreshType.refreshNpcInfo.name())){
            response = refreshNpcInfo();
        }else if(type.equals(RefreshType.refreshXingInfo.name())){
            SpringUtils.getBean(XingGuanHandler.class).loadXingGuanSet();
        }else if(type.equals(RefreshType.refreshNewBossInfo.name())){
            SpringUtils.getBean(NewBossService.class).loadProductData();
        }else if(type.equals(RefreshType.refreshChengWeiInfo.name())){
            SpringUtils.getBean(TitleInfoService.class).loadProduct();
        }else if(type.equals(RefreshType.refreshRewardInfo.name())){
            SpringUtils.getBean(RewardSetService.class).loadProduct();
        }else if(type.equals(RefreshType.refreshRedisInfo.name())){
            SpringUtils.getBean(RefreshCache.class).refreshRedisInfo();

            SpringUtils.getBean(HunPoService.class).loadShenHun();
            SpringUtils.getBean(WuHunService_.class).loadWuhun();
            SpringUtils.getBean(NeidanService.class).loadWuhun();
            //加载七日登录
            SpringUtils.getBean(ServenDayRewardHandler.class).load();
            //加载每日签到
            SpringUtils.getBean(MyApplicationRunner.class).initDaySign();
            /**加载积分抽奖数据*/
            SpringUtils.getBean(NewChouJiangService.class).load();

            //重新加载改造消耗
            SpringUtils.getBean(GSGService.class).init();
            //珍宝  集市
            SpringUtils.getBean(ZhenbaoService.class).init();
            SpringUtils.getBean(MarketService.class).init();

        }else if(type.equals(RefreshType.refreshBossNumInfo.name())){
            List<ActivityNumberSet> list = SpringUtils.getBean(Dao.class).query(ActivityNumberSet.class, Cnd.NEW());
            for (ActivityNumberSet activityNumberSet : list) {
                String activityType  = activityNumberSet.getBossType();
                ActivityType.upActivityType(activityType, activityNumberSet.getCishu());
            }
        }else if(type.equals(RefreshType.refreshChouJiangInfo.name())){
            SpringUtils.getBean(RefreshCache.class).refreshRedisInfo();
            SpringUtils.getBean(NewChouJiangService.class).load();
        }else if(type.equals(RefreshType.refreshPetSet.name())){
            Dao dao = SpringUtils.getBean(Dao.class);
            List<CommonSet> list = dao.query(CommonSet.class, Cnd.NEW());
            Map<String ,String> commonSetMap = new HashMap<>(list.size());
            for (CommonSet commonSet : list) {
                commonSetMap.put(commonSet.getSkey(), commonSet.getSvalue());
            }
            PetDataPool.loadCommonSet(commonSetMap);
            // 初始化怪物
            initMonster();
        }else if(type.equals(RefreshType.refreshTaskScheInfo.name())){

            response = refreshTaskScheInfo(value,state);
        }else if(type.equals(RefreshType.startKuafu.name())){
            AjaxResult ajaxResult = startKuaFu();
            return ajaxResult;
        }
        if(1 == response.getCode()){
            return AjaxResult.success();
        }else{
            return AjaxResult.error();
        }
    }
    public void initMonster() {
        Dao dao = SpringUtils.getBean(Dao.class);
        List<PetSet> list = dao.query(PetSet.class, Cnd.NEW());
        DataCache.MOUNTS.clear();
        DataCache.ICON_PETSET.clear();
        DataCache.NAME_ICON.clear();
        DataCache.VARIATION.clear();
        for (PetSet petSet : list) {
            DataCache.ICON_PETSET.put(petSet.getIcon(), petSet);
            DataCache.NAME_ICON.put(petSet.getName(), petSet.getIcon());
            if (petSet.getType() == 1) {
                DataCache.MOUNTS.add(petSet.getName());
            }
            if (petSet.getType1() == 3) {
                DataCache.VARIATION.add(petSet.getName());
            }
        }

    }
    //维护
    public Response maintain(String value){
        try {
            if (value != null) {
                if ("1".equals(value)) {
                    boolean flag = SessionManager.INSTANCE.killAllPlayers();
                    if (flag) {
                        ServerService.gate=1;
                    } else {
                        return Response.error("维护失败");
                    }
                } else {
                    ServerService.gate=0;
                }
            }
            Dao dao = SpringUtils.getBean(Dao.class);
            List<AppProperties> list = dao.query(AppProperties.class, Cnd.where("key_","=","gate").asc("id"));
            AppProperties appProperties = list.get(0);
            appProperties.setValue_(value);
            dao.insertOrUpdate(appProperties);
            return Response.ok();
        } catch (Exception e) {
            log.info("操作异常",e);
            return Response.error("操作异常");
        }
    }

    public Response ceshi(String value) {
        try {
            if ("100".equals(value)) {
                SpringUtils.getBean(ServerService.class).setNeice(100);

            } else {
                //公测
                SpringUtils.getBean(ServerService.class).setNeice(0);

            }
            Dao dao = SpringUtils.getBean(Dao.class);
            List<AppProperties> list = dao.query(AppProperties.class, Cnd.where("key_","=","neice").asc("id"));
            AppProperties appProperties = list.get(0);
            appProperties.setValue_(value);
            dao.insertOrUpdate(appProperties);
            return Response.ok();
        } catch (Exception e) {
            log.info("操作异常",e);
            return Response.error("操作异常");
        }
    }

    @Autowired
    AdminService adminService;
    public Response speak(String value,String state) {
        try {
            Integer roleId = Integer.valueOf(value);
            Role role = SpringUtils.getRoleService().getPlayerBy(roleId);
            if ("0".equals(state)) {
                adminService.shutChannel(role, System.currentTimeMillis() + 2400 * 60 * 60 * TimeUtil.ONE_SECOND);
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("你已被禁言!"));
                return Response.ok();
            } else {
                adminService.shutChannel(role, 0);
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("你可以畅所欲言了!"));
                return Response.ok();
            }
        } catch (Exception e) {
            log.info("操作异常",e);
            return Response.error("操作异常");
        }
    }
    //封帐号
    public Response sealPhone(String value,String state) {
        try {
            Account account = SpringUtils.getBean(AccountService.class).getAccountByUsername(value);
            if(account != null){
                if ("0".equals(state)) {
                    SpringUtils.getBean(AdminService.class).blockAccount(account);
                }else{
                    SpringUtils.getBean(AdminService.class).writeAccount(account);
                }
                return Response.ok();
            }
        } catch (Exception e) {
            log.info("操作异常",e);
            return Response.error("操作异常");
        }
        return Response.ok();
    }

    /**
     * 封角色 解封
     * @return
     */
    public Response seal(String value,String state) {
        try {
            Integer roleId = Integer.valueOf(value);
            Role role = SpringUtils.getRoleService().getPlayerBy(roleId);
            if ("0".equals(state)) {
                adminService.blockPlayer(role, System.currentTimeMillis() +  8784 * 60 * 60 * TimeUtil.ONE_SECOND);
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("你已被封禁!"));
                return Response.ok();
            } else {
                adminService.blockPlayer(role, 0);
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("你已被封禁!"));
                return Response.ok();
            }
        } catch (Exception e) {
            log.info("操作异常",e);
            return Response.error("操作异常");
        }
    }

    /**
     * T人下线
     * @return
     */
    public Response killPlayers(String value) {
        try {
                Integer roleId = Integer.valueOf(value);
                Role role = SpringUtils.getRoleService().getOnlinePlayer(roleId);
                if(role == null){
                    role = SpringUtils.getRoleService().getPlayerBy(roleId);
                    SpringUtils.getRoleService().removeOnline(role);
                    SpringUtils.getRoleService().addOffline(role);
                    return Response.ok();
                }
                IoSession iosession = SessionUtils.getSession(roleId);
                MessagePusher.pushMessage(iosession, new RespNotifyMiscEx("你已被T下线，3秒之后将断开连接"));
                ScheduledFuture<?> timeOutTask = SchedulerManager.getInstance().schedule(new Runnable() {
                    @Override
                    public void run() {
                        SessionManager.INSTANCE.closeSession(iosession);
                    }
                }, 3000);
                SpringUtils.getRoleService().removeOnline(role);
                SpringUtils.getRoleService().addOffline(role);
            return Response.ok();
        } catch (Exception e) {
            log.info("操作异常",e);
            return Response.error("操作异常");
        }
    }
    @Autowired
    private ChatService chatService;
    /**
     *  公告
     * @return
     */
    public Response notice(String value) {
        try {
            chatService.sendAdnotice(value);
            return Response.ok();
        } catch (Exception e) {
            log.info("操作异常",e);
            return Response.error("操作异常");
        }
    }

    public Response refreshNpcInfo() {
        try {
            log.info("正在刷新NPC配置...");
            SpringUtils.getBean(MyApplicationRunner.class).initNpc();
            log.info("刷新CPN配置成功...");
            Dao dao = SpringUtils.getBean(Dao.class);
            List<CommonSet> list = dao.query(CommonSet.class, Cnd.NEW());
            Map<String ,String> commonSetMap = new HashMap<>(list.size());
            for (CommonSet commonSet : list) {
                commonSetMap.put(commonSet.getSkey(), commonSet.getSvalue());
            }
            SpringUtils.getBean(ZhengDaoDianHandler.class).loadCommonSet(commonSetMap);
            return Response.ok();
        } catch (Exception e) {
            log.info("操作异常",e);
            return Response.error("操作异常");
        }
    }


    @Autowired
    private ApplicationContext context;
    @Autowired
    private SpringScheduledCronService cronRepository;
    @Autowired
    CronTaskRegistrar cronTaskRegistrar;
    public Response refreshTaskScheInfo(String value,String state) {
        try {
            log.info("正在刷新定时任务配置...");
            List<SpringScheduledCron> SpringScheduledCronList =  SpringUtils.getBean(Dao.class).query(SpringScheduledCron.class, Cnd.where("cron_id", "=", value));
            if(SpringScheduledCronList.size()>0){
                SpringScheduledCron springScheduledCron = SpringScheduledCronList.get(0);
                Class<?> clazz;
                Object task;
                try {
                    clazz = Class.forName(springScheduledCron.getCron_key());
                    task = SpringUtils.getBean(clazz);
                  //  task = context.getBean(clazz);
                } catch (ClassNotFoundException e) {
                    throw new IllegalArgumentException("spring_scheduled_cron表数据" + springScheduledCron.getCron_key() + "有误", e);
                } catch (BeansException e) {
                    throw new IllegalArgumentException(springScheduledCron.getCron_key() + "未纳入到spring管理", e);
                }
                Assert.isAssignable(ScheduledOfTask.class, task.getClass(), "定时任务类必须实现ScheduledOfTask接口");
                // 可以通过改变数据库数据进而实现动态改变执行周期
                if("1".equals(state)){
                    String cronExpression = cronRepository.findByCronKey(springScheduledCron.getCron_key()).get(0).getCron_expression();
                    cronTaskRegistrar.addCronTask((Runnable) task,cronExpression);
                }else{
                    cronTaskRegistrar.removeCronTask((Runnable)task);
                }
                log.info("刷新"+springScheduledCron.getTask_explain()+"定时任务配置成功...");
            }
            //newBossService.loadProductData();

            return Response.ok();
        } catch (Exception e) {
            log.info("操作异常",e);
            return Response.error("操作异常");
        }
    }

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        int  h= calendar.get(Calendar.HOUR_OF_DAY);
        int m = calendar.get(Calendar.MINUTE);

        System.out.println(h);
        System.out.println(m);
        calendar.add(Calendar.HOUR,1);
          h= calendar.get(Calendar.HOUR_OF_DAY);
        System.out.println(h);
    }
    public AjaxResult  startKuaFu(){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,1);
        int  h= calendar.get(Calendar.HOUR_OF_DAY);
        int m = calendar.get(Calendar.MINUTE);
        String content = h+"##"+m;
        String[] strings = content.split("##");
        if (SpringUtils.getBean(ServerService.class).getServer().getId() == 10000) {
            // 通知开启跨服试道
            Map<String, Object> params = new HashMap<>();
            params.put("content", content);
            try {
                List<LoginServer> list = SpringUtils.getBean(AccountService.class).queryServer();
                for (LoginServer server : list) {
                    Request request = Request.create(server.getUrl() + "/haitang/scl/my/startKuafu", Request.METHOD.POST).setParams(params);
                    Sender.create(request).setTimeout(2000).send();
                }
                SpringUtils.getBean(PlayerService.class).delKuafuRole();
                SpringUtils.getBean(ShiDaoHandler.class).setStartH(Integer.parseInt(strings[0]));
                SpringUtils.getBean(ShiDaoHandler.class).setStartM(Integer.parseInt(strings[1]));
                SpringUtils.getBean(ShiDaoHandler.class).prepareOnceShiDao();
            } catch (Exception e) {
                return AjaxResult.error("开启跨服试道失败");
            }
            return AjaxResult.success();
        }else{
            return AjaxResult.error("跨服专线才可开启跨服试道");
        }
    }
}
